﻿/**

 @Name：主题设置
 @Author：Zxq
 @License：MIT
    
 */
layui.use(['layer', 'colorpicker', 'form'], function (exports) {
    var $ = layui.jquery, form = layui.form, colorpicker = layui.colorpicker, unfinished = '暂未实现';
    var colorArray=[{id:'theme-custom-color',name:'选择主题色'},
                    {id:'taskbar-bgColor',name:'任务栏背景色',css:'--taskbar-color',diff:[0,0,0]},
                    {id:'taskbar-hover',name:'任务项悬浮背景色',css:'--taskbar-hover',diff:[25,21,17]},
                    {id:'taskbar-focus',name:'任务项选中背景色',css:'--taskbar-focus',diff:[0,21,28]},
                    {name:'已开任务项标记颜色',css:'--taskbar-border',color:'#fff'},//,diff:[118,135,157]暂不做设置
                    {id:'start-bgColor',name:'菜单栏背景色',css:'--start-color',diff:[0,21,28]},
                    {id:'start-hover',name:'菜单项悬浮背景色',css:'--start-hover',diff:[31,100,155]},
                    {id:'start-tile',name:'菜单栏磁贴背景色',css:'--start-tile',diff:[0,44,98]},
                    {name:'菜单项图标背景色',css:'--start-icon',sameWith:'--start-tile'},//参照样式--start-tile
                    {name:'磁贴边框颜色',css:'--start-border',sameWith:'--taskbar-border'},//参照样式--taskbar-boreder
                    {id:'win-bgColor',name:'窗口颜色',css:'--win-color',diff:[0,0,0]},
                    {name:'窗口标题栏字体颜色',css:'--win-font',color:'#fff'},//固定颜色
                    {id:'win-hover',name:'窗口按钮悬浮背景色',css:'--win-hover',diff:[10,10,10]},
                    {name:'窗口边框颜色',css:'--win-border',sameWith:'--win-hover'},//参照样式--win-hover
                    {id:'other-bgColor',name:'其它背景色',css:'--other-color',diff:[20,20,20]},
                    {id:'other-hover',name:'其它悬浮背景色',css:'--other-hover',diff:[25,40,52]},
                    {name:'其它边框颜色',css:'--other-border',diff:[30,30,30]}];

    $(function () {
        swui.renderColor();
        swui.tabInit('.swui-tab');
        if (tabIndex != null)
            $('.swui-tab-nav').children('li').eq(tabIndex).trigger('click');
        //swui.tabOn('tabchange()', function (data) { console.log(data); });
        //设置预览背景为当前背景
        $('.background-preview').css('background-image', $('body').css('background-image'));
        //设置锁屏预览背景为当前锁屏预览背景
        $('.lockscreen-preview').css('background-image', 'url(' + swui.getSetting('lockBgSrc') + ')');

        //设置任务栏是否自动隐藏
        var taskbarHide = swui.getSetting('taskbarHide');
        $('input[lay-filter="toggleTaskbar"]').prop('checked', taskbarHide).siblings('span').text(taskbarHide ? '开' : '关');;
        //设置主题预览中任务栏位置
        var taskbarMode = swui.getSetting('taskbarMode');
        $('.taskbar-position input[value=' + taskbarMode + ']').prop('checked', true);
        $('input[lay-filter="taskbarMode"]').prop('value',taskbarMode);
        //设置主题预览中开始菜单尺寸
        var startSize = swui.getSetting('startSize');
        $('.start-size input[value=' + startSize + ']').prop('checked', true);
        $('.preview-start').removeClass('xs sm lg');
        $('.preview-start').addClass(startSize);
        //自定义主题色
        swui.getSetting('customColors').forEach(function(item, index){
            $('.theme-color-new').before('<div class="theme-color-'+item.id+' custom" title="'+item.title+'"><div class="edit" title="编辑"><i class="layui-icon layui-icon-edit"></i></div><div class="delete" title="删除"><i class="layui-icon layui-icon-delete"></i></div></div>');
            layxwin.setStyle(".theme-color-"+item.id+" {background-color:"+item.color+";}");
        });

        $('.color-choose .theme-color-'+swui.getSetting('color')).addClass('on');

        var html = '<div class="layui-form-item"><div class="layui-inline"><label class="layui-form-label">'+colorArray[0].name+'</label><div id="'+colorArray[0].id+'"></div></div><div class="layui-inline"><input type="text" id="theme-custom-title" autocomplete="off" placeholder="主题名称" class="layui-input" style="width:192px;"></div></div>';
        html += '<fieldset class="theme-custom-title"><legend>相关颜色预设</legend></fieldset><div class="layui-form-item">';
        for (var i=1;i<colorArray.length;i++) {
            var item = colorArray[i];
            if (!item.id) continue;
            html += '<div class="layui-inline"><label class="layui-form-label">'+item.name+'</label><div id="'+item.id+'"></div></div>';
        }
        html += '</div><div><div class="btn complete">完成</div><div class="btn cancel">取消</div></div>';
        $('.theme-custom').append(html);

        form.render();

        //预览锁屏界面
        var Week = ['日', '一', '二', '三', '四', '五', '六'];
        var dateTime = new Date();
        $('.lockscreen-preview-time').html('<p id="time">' + (dateTime.getHours() > 9 ? dateTime.getHours().toString() : '0' + dateTime.getHours()) + ':' + (dateTime.getMinutes() > 9 ? dateTime.getMinutes().toString() : '0' + dateTime.getMinutes()) + '</p><p id="date">' + (dateTime.getMonth() + 1) + '月' + dateTime.getDate() + '日,星期' + Week[dateTime.getDay()] + '</p>');
        var cps = {};
        colorArray.forEach(function(item,index){
            if (!item.id) return;
            var cp = colorpicker.render({
                elem: '#'+item.id
                ,done: function(color){
                    item.color = color;
                    if (item.id === 'theme-custom-color') {
                        for(var i=1;i<colorArray.length;i++) {
                            if (!colorArray[i].diff) continue;
                            colorArray[i].color = changeColor(color, colorArray[i].diff);
                            if (colorArray[i].id)
                                cps[colorArray[i].id].setColor(colorArray[i].color);
                            //$('#'+colorArray[i].id).css('background-color',colorArray[i].color);
                        }
                    }
                    else {
                        for(var i=1;i<colorArray.length;i++) {
                            if (colorArray[i].id === item.id) {
                                colorArray[i].color = color;
                                break;
                            }
                        }
                    }
                }
            });
            cps[item.id] = cp;
        });
        //背景图片点击
        $('.background-choose>img').on('click', function () {
            //获取当前图片路径
            var bgSrc = $(this).prop('src');
            //改变预览背景
            $('.background-preview').css('background-image', 'url(' + bgSrc + ')');
            //改变父页面背景
            swui.resetBg(bgSrc);
        })
        //背景图片上传
        $('.background-upload').on('click', function () {
            var input = $(this).prev('input[type=file]');
            input.trigger('click');
            input.on('change', function () {
                var src = $(this).val();
                if (src) {
                    layer.msg('选择了路径【' + src + '】下的图片，返回一张性感的Girl给你')
                    //改变预览背景
                    $('.background-preview').css('background-image', 'url(images/sexy_girl.jpg)');
                    //改变父页面背景
                    swui.resetBg('images/sexy_girl.jpg');
    
                    $(this).val('').off('change');
                }
            })
        });
        //锁屏界面点击
        $('.lockscreen-choose>img').on('click', function () {
            //获取当前图片路径
            var bgSrc = $(this).prop('src');
            //改变锁屏预览
            $('.lockscreen-preview').css('background-image', 'url(' + bgSrc + ')');
            //设置锁屏背景
            swui.resetLockBg(bgSrc);
        })
        //锁屏界面图片上传
        $('.lockscreen-upload').on('click', function () {
            var input = $(this).prev('input[type=file]');
            input.trigger('click');
            input.on('change', function () {
                var src = $(this).val();
                if (src) {
                    layer.msg('选择了路径【' + src + '】下的图片，返回一张性感的Girl给你')
                    //改变锁屏预览
                    $('.lockscreen-preview').css('background-image', 'url(images/sexy_girl.jpg');
                    //设置锁屏背景
                    swui.resetLockBg('images/sexy_girl.jpg');
                    $(this).val('').off('change');
                }
            })
        });
        var themeid;
        //颜色选择
        $('.color-choose').on('click', '>div', function () {
            if ($(this).hasClass('theme-color-new')) {
                themeid='';
                $('.theme-custom.layui-hide').removeClass('layui-hide');
                return;
            }
            else if ($(this).hasClass('theme-custom'))
                return;
            $(this).addClass('on').siblings().removeClass('on');
            var color = $(this)[0].classList[0].replace('theme-color-', '');
            swui.resetColor(color);
        });
        $('.color-choose').on('click', '>div.custom >div', function (e) {
            themeid = $(this).parent()[0].classList[0].replace('theme-color-', '');
            if ($(this).hasClass('edit')) {
                $('.theme-custom.layui-hide').removeClass('layui-hide');
                var index = swui.Utils.indexOfObjectInArray('id',{id:themeid},swui.settings.customColors);
                if (index > -1) {
                    var cs = swui.settings.customColors[index];
                    $('#theme-custom-title').val(cs.title);
                    cps['theme-custom-color'].setColor(cs.color);
                    cs = cs.style;
                    for (var i=0;i<cs.length;i++) {
                        if (!cs[i].id) continue;
                        cps[cs[i].id].setColor(cs[i].color);
                    }
                }
            }
            else if ($(this).hasClass('delete')) {
                var title = $(this).parent().attr('title');
                layer.confirm('是否删除自定义主题'+title+'?', {icon: 3, title:'提示'}, function(index){
                    var flag = swui.removeColor(themeid);
                    if (flag) {
                        $('div.theme-color-'+themeid).remove();
                        $('div.theme-color-'+swui.getSetting('color')).addClass('on').siblings().removeClass('on');
                    }
                    layer.close(index);
                });
            }
            swui.sp(e);
        });
        $('.theme-custom').on('click', '.btn', function(){
            if ($(this).hasClass('complete')) {
                for (var j=0;j<colorArray.length;j++){
                    if (!colorArray[j].id) continue;
                    colorArray[j].color = cps[colorArray[j].id].getColor();
                }
                var s=[];
                for(var i=0;i<colorArray.length;i++){
                    if (!colorArray[i].css) continue;
                    if (colorArray[i].color) {
                        //s+=colorArray[i].css + ':'+colorArray[i].color+';';
                        s.push({id:colorArray[i].id,css:colorArray[i].css,color:colorArray[i].color});
                    }
                    else if (colorArray[i].sameWith) {
                        for(var j=0;j<colorArray.length;j++){
                            if (i === j) continue;
                            if (colorArray[i].sameWith === colorArray[j].css) {
                                //s+=colorArray[i].css + ':'+colorArray[j].color+';';
                                s.push({id:colorArray[i].id,css:colorArray[i].css,color:colorArray[j].color});
                                break;
                            }
                        }
                    }
                }
                var title = $('#theme-custom-title').val();
                s = swui.renderColor({id:themeid,color:colorArray[0].color,style:s,title:title});
                if (!s) return;
                $('.color-choose div.on').removeClass('on');
                var th = $('div.theme-color-'+s);
                if (th.length === 0) {//新增
                    layxwin.setStyle(".theme-color-"+s+" {background-color:"+colorArray[0].color+";}");
                    $('.theme-color-new').before('<div class="theme-color-'+s+' custom on" title="'+title+'"><div class="edit" title="编辑"><i class="layui-icon layui-icon-edit"></i></div><div class="delete" title="删除"><i class="layui-icon layui-icon-delete"></i></div></div>');
                }
                else {
                    th.addClass('on').attr('title',title).css('background-color',colorArray[0].color);
                }
            }
            $('.theme-custom').addClass('layui-hide');
        });
    
        form.on('switch(toggleTransparent)', function (data) {
            if (data.elem.checked) {
                $(data.elem).siblings('span').text('开');
            } else {
                $(data.elem).siblings('span').text('关');
            }
            layer.msg(unfinished);
        });
    
        form.on('switch(toggleTaskbar)', function (data) {
            if (data.elem.checked) {
                swui.setTaskBarHide('set');
                $(data.elem).siblings('span').text('开');
            } else {
                swui.setTaskBarHide();
                $(data.elem).siblings('span').text('关');
            }
        });
        //任务栏位置
        form.on('radio(taskPosition)', function (data) {
            swui.resetTaskbar(data.value);
        });
        form.on('btns(taskbarMode)', function (data) {
            swui.resetTaskbar(data.value);
        });
        //开始菜单尺寸
        form.on('radio(startSize)', function (data) {
            swui.resetStartSize(data.value);
        });
    });
    function gradientColor(startColor,endColor,step){
        startRGB = HexToRGB(startColor);//转换为rgb数组模式
        startR = startRGB[0];
        startG = startRGB[1];
        startB = startRGB[2];

        endRGB = HexToRGB(endColor);
        endR = endRGB[0];
        endG = endRGB[1];
        endB = endRGB[2];

        sR = (endR-startR)/step;
        sG = (endG-startG)/step;
        sB = (endB-startB)/step;

        var colorArr = [];
        for(var i=0;i<step;i++){
            //计算每一步的hex值
            var hex = RGBToHex('rgb('+parseInt((sR*i+startR))+','+parseInt((sG*i+startG))+','+parseInt((sB*i+startB))+')');
            colorArr.push(hex);
        }
        return colorArr;
    }
    function changeColor(hexColor, diff) {
        if (!diff || diff.length !== 3)
            return hexColor;
        var startRGB = HexToRGB(hexColor);//转换为rgb数组模式
        var endR = startRGB[0] + diff[0],
        endG = startRGB[1] + diff[1],
        endB = startRGB[2] + diff[2];
        if (endR > 255) endR -= 255;
        else if (endR < 0) endR += 255;
        if (endG > 255) endG -= 255;
        else if (endG < 0) endG += 255;
        if (endB > 255) endB -= 255;
        else if (endB < 0) endB += 255;
        var hex = RGBToHex('rgb('+parseInt(endR)+','+parseInt(endG)+','+parseInt(endB)+')');
        return hex;
    }
    // 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
    function HexToRGB(hexColor) {
        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        var sColor = hexColor.toLowerCase();
        if(sColor && reg.test(sColor)){
            if(sColor.length === 4){
                var sColorNew = "#";
                for(var i=1; i<4; i++){
                    sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));
                }
                sColor = sColorNew;
            }
            //处理六位的颜色值
            var sColorChange = [];
            for(var i=1; i<7; i+=2){
                sColorChange.push(parseInt("0x"+sColor.slice(i,i+2)));
            }
            return sColorChange;
        }else{
            return sColor;
        }
    }
    // 将rgb表示方式转换为hex表示方式
    function RGBToHex(rgbColor) {
        var _this = rgbColor;
        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        if(/^(rgb|RGB)/.test(_this)){
            var aColor = _this.replace(/(?:(|)|rgb|RGB)*/g,"").split(",");
            var strHex = "#";
            for(var i=0; i<aColor.length; i++){
                var hex = Number(aColor[i]).toString(16);
                hex = hex<10 ? 0+''+hex :hex;// 保证每个rgb的值为2位
                if(hex === "0"){
                    hex += hex;
                }
                strHex += hex;
            }
            if(strHex.length !== 7){
                strHex = _this;
            }
            return strHex;
        }else if(reg.test(_this)){
            var aNum = _this.replace(/#/,"").split("");
            if(aNum.length === 6){
                return _this;
            }else if(aNum.length === 3){
                var numHex = "#";
                for(var i=0; i<aNum.length; i+=1){
                    numHex += (aNum[i]+aNum[i]);
                }
                return numHex;
            }
        }else{
            return _this;
        }
    }
});